#include <stdio.h>
#include <pthread.h>
typedef struct
{
	int deposit;
	pthread_mutex_t lock;// 把锁与变量联系在一起
}Account;
typedef struct
{
	char name[8];
	int amount;
	Account* account;
}User;
void* withdraw(void*);
int main(void)
{
	Account account = {88888};
	pthread_mutex_init(&account.lock,NULL);
	User user1 = {"jin1",88888,&account};
	User user2 = {"jin2",88888,&account};
	pthread_t thread1_id,thread2_id;
	int res = 0;
	if((res = pthread_create(&thread1_id,NULL,withdraw,(void*)&user1)) != 0)
	{
		perror("create thread error");
	}
	if((res = pthread_create(&thread2_id,NULL,withdraw,(void*)&user2)) != 0)
	{
		perror("create thread error");
	}
	pthread_join(thread1_id,NULL);
	pthread_join(thread2_id,NULL);
	printf("account's deposit %d\n",account.deposit);
	return 0;
}
void* withdraw(void* user)
{
	User* u = (User*)user;
	// 加锁，其他线程到这里加锁时会阻塞住，等解锁后才会继续运行
	pthread_mutex_lock(&u->account->lock);
	sleep(1);
	if(u->amount > u->account->deposit)
	{
		printf("sorry %s;your balance is not enough\n",u->name);
		return (void*)NULL;
	}
	printf("%s => %d\n",u->name,u->amount);
	u->account->deposit -= u->amount;
	// 解锁，解锁后其他线程才会继续运行
	pthread_mutex_unlock(&u->account->lock);
	return (void*)NULL;
}
